package net.diaowen.dwsurvey.controller;

import net.diaowen.common.base.entity.Org;
import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.entity.WcUser;
import net.diaowen.common.base.entity.WcUserDetail;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.utils.SystemUtils;
import net.diaowen.common.utils.weixin.CreateMenu;
import net.diaowen.common.utils.weixin.WechatProcess;
import net.diaowen.dwsurvey.entity.LotteryActivity;
import net.diaowen.dwsurvey.entity.StudentLottery;
import net.diaowen.dwsurvey.entity.StudentSurvey;
import net.diaowen.dwsurvey.entity.SurveyDirectory;
import net.diaowen.dwsurvey.service.*;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.octo.captcha.service.image.ImageCaptchaService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.diaowen.common.utils.DiaowenProperty;
import net.diaowen.common.utils.weixin.SignUtil;
import net.diaowen.common.utils.weixin.WeChatUtil;


/**
 * Created by limeng on 6/5/2019.
 */

@Controller
@RequestMapping("/wexin")
public class WechatController {


    @Resource(name="redisTemplate")
    private RedisTemplate redisTemplate;

	@Autowired
	private ImageCaptchaService imageCaptchaService;
	
    @Autowired
    private AccountManager accountManager;

    @Autowired
    private WechatManager wechatManager;   
    
    @Autowired
    private OrgManager orgManager;
    
    @Autowired
    private UserManager userManager;
    
    @Autowired
    private SurveyDirectoryManager surveyDirectoryManager;
    
    @Autowired
    private LotteryUserManager lotteryUserManager;
    
    @Autowired
    private StudentLotteryManager studentLotteryManager;
    @Autowired
    private LotteryActivityManager lotteryActivityManager;

    
    @RequestMapping("/coreServlet.do")
    public void checkUrlAndToken(HttpServletRequest request, HttpServletResponse response, String surveyId) throws Exception {

        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戮
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        String result = "";

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        /** 读取接收到的xml消息 */
        StringBuffer sb = new StringBuffer();
        InputStream is = request.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String s = "";
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }

        String xml = sb.toString();

        // 通过检验 signature 对请求进行校验，若校验成功则原样返回 echostr，表示接入成功，否则接入失败
        if (echostr != null && echostr.length() > 1) {
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                result = echostr;
                System.out.println("+++微信校验成功+++");

            }
        } else {
            //正常的微信处理流程
            result = new WechatProcess().processWechatMag(xml);
            String openId = (String) request.getSession().getAttribute("openId");

            if (openId == null) {
            	request.getSession().setAttribute("openId", result);
            }
            System.out.println("return msg:" + xml);
            // CreateMenu.createMenu();
        }
        PrintWriter out = response.getWriter();
        try {
            out.write(result);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }



    @RequestMapping("/bind.do")
    public ModelAndView myaccount(HttpServletRequest request,HttpServletResponse response, String code) throws Exception {
         //判断openId入口是否从url点击进入,如果不是则是从菜单进入
    	String openId = request.getParameter("openId");
    	if (openId == null) {
    		openId = WeChatUtil.getAccessOpenId(code);
    	}
    	System.out.println("the openid is:"+openId);
    	//将openId存入session
    	request.getSession().setAttribute("openId", openId);
        ModelAndView modelAndView = new ModelAndView();
        //如果已经绑定了，直接跳转到我的问卷画面
        WcUser wcUser = wechatManager.findUserByWxid(openId);
        if (wcUser != null) {
            //将这个用户存入Session
            User wxUser = userManager.get(wcUser.getUserId());
            request.getSession().setAttribute("wxUser", wxUser);
            return new ModelAndView("redirect:mySurvey.do");
        } else {
            List<Org> orgList = orgManager.findList();
            modelAndView.addObject("orgList", orgList);
            modelAndView.setViewName("/diaowen-weixin/bindUser");
        }
        return modelAndView;
    }

    @RequestMapping("/game.do")
    public ModelAndView game(HttpServletRequest request,HttpServletResponse response, String code) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/diaowen-weixin/game");
        return modelAndView;
    }
    
    @RequestMapping("/gameAjaxInit.do")
    public String gameInit(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	//从session获取surveyId
    	String surveyId = (String) request.getSession().getAttribute("wxSurveyId");
    	String openId = (String) request.getSession().getAttribute("openId");
    	//String surveyId = "402868816bac9562016bac9600ee0000";
    	//String openId = "oz0Fg5nxp6K4MNqlrgjDofOiOTp4";
    	Map<String, Object> initLotteryPage = lotteryUserManager.initLotteryPage(surveyId, openId);
    	String result = new JSONObject(initLotteryPage).toString();
    	response.getWriter().write(result);
        return null;
    }
    
    @RequestMapping("/gameAjaxLottery.do")
    public String gameLottery(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	//从session获取surveyId
    	String openId = (String) request.getSession().getAttribute("openId");
    	String answerId = (String) request.getSession().getAttribute("wxAnswerId");
    	Map resultMap = lotteryUserManager.findUserLotterPrize(answerId, openId);
    	//如果成功了就将session清除掉
    	if (resultMap.get("status") != null && resultMap.get("status").equals("0")) {
    		request.getSession().removeAttribute("wxAnswerId");
    	}
    	String result = new JSONObject(resultMap).toString();
    	response.getWriter().write(result);
        return null;
    }

    @RequestMapping("/bindAjax.do")
    @ResponseBody
    public String myaccountSave(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	//从session获取openId
    	String openId = (String) request.getSession().getAttribute("openId");
    	String orgId = request.getParameter("orgId");
    	String studentId = request.getParameter("studentId");
    	String vcode = request.getParameter("vcode");
    	
    	//验证码check
    	Boolean vcodeFlag = imageCaptchaService.validateResponseForID(request.getSession().getId(), vcode);
    	if (!vcodeFlag) {
        	response.getWriter().write("0");
        	return null;
    	} 
    	
    	//机构或学号check
    	User u1 = userManager.findOrgStudentId(orgId, studentId);
    	if (u1 == null) {
        	response.getWriter().write("1");
        	return null;
    	}
    	
    	//是否已绑定check
    	WcUser wcU1 = wechatManager.findUserByUserid(u1.getId());
    	if (wcU1 != null) {
    		String orgOpenId = wcU1.getWxId();
    		//解绑
    		wechatManager.delete(wcU1);
            //消息模板或客服消息推送给orgOpenId 目前采用客服模式
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeChatUtil.getAccessToken().getToken();
            String outputStr = "{\"touser\":\""+orgOpenId+"\",\"msgtype\":\"text\",\"text\":{\"content\":\"老弟，你号被盗了\"}}";
            WeChatUtil.httpRequest(requestUrl, "POST", outputStr);

    	}
    	//绑定
    	WcUser wcU2 = new WcUser();
    	wcU2.setBandTime(new Date());
    	wcU2.setUserId(u1.getId());
    	wcU2.setWxId(openId);
    	wechatManager.save(wcU2);
        request.getSession().setAttribute("wxUser", u1);
    	response.getWriter().write("2");
    	return null;
    }
    
    @RequestMapping("/mySurvey.do")
    public ModelAndView mySurvey(HttpServletRequest request,HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        try {
            User wxUser = (User) request.getSession().getAttribute("wxUser");
            List<StudentSurvey> studentSurveyList = surveyDirectoryManager.findByUser(wxUser);
            modelAndView.addObject("surveyList", studentSurveyList);
            modelAndView.addObject("baseUrl", DiaowenProperty.BASE_URL);
            modelAndView.setViewName("/diaowen-weixin/my_survey");
        }catch (Exception e){
              e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping("/myInfo.do")
    public ModelAndView myInfo(HttpServletRequest request,HttpServletResponse response,String flag,String surveyId) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("surveyId")==null&&surveyId!=null)
        {
            session.setAttribute("surveyId",surveyId);
        }
        ModelAndView modelAndView = new ModelAndView();
    	String wxid = (String) request.getSession().getAttribute("openId");
    	WcUserDetail wcDB = wechatManager.getWcUserDetail(wxid);
    	modelAndView.addObject("entity",wcDB);
        modelAndView.addObject("flag",flag);
        modelAndView.setViewName("/diaowen-weixin/my_info");
        return modelAndView;
    }
    
    @RequestMapping("/saveMyInfo.do")
    public ModelAndView saveMyInfo(HttpServletRequest request,HttpServletResponse response,WcUserDetail wcForm,String flag) throws Exception {


        ModelAndView modelAndView = new ModelAndView();
        String wxid = (String) request.getSession().getAttribute("openId");
        WcUserDetail wcDB = wechatManager.getWcUserDetail(wxid);
        System.out.println("wcForm.getName() = " + wcForm.getName());
        System.out.println("wcForm.getPhone() = " + wcForm.getPhone());
        if (wcForm.getName().length()==0)
        {
            System.out.println("wcForm.getName() = " + wcForm.getName());
            modelAndView.addObject("error","0");
            modelAndView.setViewName("/diaowen-weixin/my_info");
            return modelAndView;
        }
        if (wcDB == null) {
            wcForm.setId(null);
            wcForm.setWxId(wxid);
            wechatManager.saveWcUserDetail(wcForm);
            modelAndView.addObject("entity", wcForm);
        } else {
            wcDB.setName(wcForm.getName());
            wcDB.setPhone(wcForm.getPhone());
            wcDB.setAddress(wcForm.getAddress());
            wcDB.setZipcode(wcForm.getZipcode());
            wechatManager.saveWcUserDetail(wcDB);
            modelAndView.addObject("entity", wcDB);
        }
        modelAndView.addObject("success", "0");

        if (flag.equals("0")) {
            // String surveyId = (String) request.getSession().getAttribute("surveyId");
            // LotteryActivity entity = lotteryActivityManager.getBySurveyId(surveyId);
            // String ImgBase643 = SystemUtils.fileToBase64(System.getProperty("user.home") + entity.getWxQRcode());
            // System.out.println("ImgBase643 = " + ImgBase643);
            // HttpSession session = request.getSession();
            // session.setAttribute("WxQRcode",entity.getWxQRcode());
            // session.setAttribute("flag",flag);
            // session.setAttribute("WxImgBase643",ImgBase643);
            // modelAndView.setViewName("/diaowen-weixin/my_contact");
            // return modelAndView;
            modelAndView.addObject("flag",flag);
        }
        modelAndView.setViewName("/diaowen-weixin/my_info");
        return modelAndView;
    }

    @RequestMapping("/myPrize.do")
    public ModelAndView myPrize(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	ModelAndView modelAndView = new ModelAndView();
    	String wxid = (String) request.getSession().getAttribute("openId");
    	List<StudentLottery> stList = studentLotteryManager.findListByWxid(wxid);
    	modelAndView.addObject("stList",stList);
        modelAndView.setViewName("/diaowen-weixin/my_prize");
        return modelAndView;
    }

    //通过活动id查询活动中所使用的二维码，并显示到my_info页面
    //活动id和使用session获取微信id
    //再使用userid得到微信id，在通过微信id得到myinfo的东西
    @RequestMapping("/Presentcontact.do")
    public ModelAndView Presentcontact(HttpServletRequest request,String flag){

        // System.out.println("进入了Presentcontact");
        ModelAndView modelAndView = new ModelAndView();
        // System.out.println("Presentcontact中flag = " + flag);
        String wxid = (String) request.getSession().getAttribute("openId");
        WcUserDetail wcDB = wechatManager.getWcUserDetail(wxid);
        modelAndView.addObject("entity",wcDB);
        if ("".equals(flag))//从头像进来的，不能显示二维码，跳转回原先的界面
        {
            modelAndView.setViewName("/diaowen-weixin/my_info");
            return modelAndView;
        }
        String surveyId = (String) request.getSession().getAttribute("surveyId");

        // System.out.println("wxid = " + wxid);
        // System.out.println("surveyId = " + surveyId);
       try{
            // 1、使用活动id读取二维码
            LotteryActivity entity = lotteryActivityManager.getBySurveyId(surveyId);
            // System.out.println("entity.getWxQRcode() = " + entity.getWxQRcode());
            String ImgBase643 = SystemUtils.fileToBase64(System.getProperty("user.home")+entity.getWxQRcode());
            // 2使用wx_id到UserDetail里获取个人信息
            modelAndView.addObject("ImgBase643",ImgBase643);
            modelAndView.addObject("WxQRcode",entity.getWxQRcode());
            modelAndView.addObject("flag","0");//二维码的显示
            modelAndView.setViewName("/diaowen-weixin/my_contact");
        }catch (Exception e) {
               e.printStackTrace();
           }
        return modelAndView;
    }

    @RequestMapping("/particulars.do")
    public ModelAndView particulars(HttpServletRequest request, HttpServletResponse response,String notice) throws Exception {
        // System.out.println("进入通知详情页面啦啦啦啦啦啦啦啦啦啦啦啦");
        // 判断openId入口是否从url点击进入,如果不是则是从菜单进入
        String openId = request.getParameter("toUser");
        System.out.println("notice = " + notice);
        // if (openId == null) {
        //     openId = WeChatUtil.getAccessOpenId(code);
        // }
        System.out.println("the openid is:"+openId);
        //将openId存入session
        request.getSession().setAttribute("openId", openId);
        ModelAndView modelAndView = new ModelAndView();
        //如果已经绑定了，直接跳转到通知详情页面
        WcUser wcUser = wechatManager.findUserByWxid(openId);
        if (wcUser != null) {
            //将这个用户存入Session
            User wxUser = userManager.get(wcUser.getUserId());
            System.out.println("wxUser.getLoginName() = " + wxUser.getLoginName());
            request.getSession().setAttribute("wxUser", wxUser);
            modelAndView.addObject("notice",notice);
            modelAndView.setViewName("/diaowen-usergroup/group-notices");
            return modelAndView;
            // return new ModelAndView("redirect:mySurvey.do");
        } else {
            List<Org> orgList = orgManager.findList();
            modelAndView.addObject("orgList", orgList);
            modelAndView.setViewName("/diaowen-weixin/bindUser");
        }
        modelAndView.setViewName("/diaowen-usergroup/group-notices");
        return modelAndView;
    }

}
